package com.vectquant.lwwl_service01.service.imp;


import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.vectquant.lwwl_service01.dto.ChatRequest;
import com.vectquant.lwwl_service01.dto.ChatResponse;
import com.vectquant.lwwl_service01.model.ChatHistory;
import com.vectquant.lwwl_service01.repository.ChatHistoryRepository;
import com.vectquant.lwwl_service01.service.AiChatService;
import com.vectquant.lwwl_service01.util.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class QwenAiServiceImpl implements AiChatService {
    private final  ChatHistoryRepository chatHistoryRepository;
    public QwenAiServiceImpl(ChatHistoryRepository chatHistoryRepository){
        this.chatHistoryRepository=chatHistoryRepository;
    }
    @Value("https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation")
    private String apiUrl;
    @Value("${aliyun.dashscope.api-key}")
    private String apiKey;
    private final ObjectMapper objectMapper= new ObjectMapper();
    /**
     * 与AI聊天并获取回复
     */
    @Override
    public ChatResponse chatWithAI(ChatRequest request){
        try{

//            设置请求头
            Map<String ,String> headers = new HashMap<>();
            headers.put("Content-Type","application/json");
            headers.put("Authorization","Bearer " + apiKey);
            //构建请求体
//            Map<String,Object> requestBody = new HashMap<>();
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", "qwen-plus");

//            构建模型输入
         /**   Map<String,Object> input = new HashMap<>();
//            构建参数
            Map<String ,Object> parameters = new HashMap<>();
            parameters.put("result_format","text");
            requestBody.put("model","qwen-plus");
            requestBody.put("input",input);
            requestBody.put("parameters",parameters);
          */
         List<Map<String ,String >> messages = new ArrayList<>();
            Map<String ,String> message = new HashMap<>();
            message.put("role","user");
            message.put("content",request.getMessage());
            messages.add(message);

            Map<String ,Object> input = new HashMap<>();
            input.put("messages",messages);
//            requestBody.put("model","qwen-plus");
            requestBody.put("input",input);
            Map<String ,Object> parameters = new HashMap<>();
            parameters.put("result-format","text");
            requestBody.put("parameters",parameters);
//            发送请求到千问API
            String response = HttpUtil.post(apiUrl,objectMapper.writeValueAsString(requestBody),headers);
//            解析响应
            JsonNode rootNode = objectMapper.readTree(response);
            String apiResponse = rootNode.path("output").path("text").asText();
//            保存聊天记录到数据库
            ChatHistory chatHistory = new ChatHistory(
                    request.getUserId(),
                    request.getMessage(),
                    apiResponse
            );
            chatHistoryRepository.save(chatHistory);
//            返回成功响应
            return new ChatResponse(true,"请求成功",apiResponse);
        }catch (Exception e){
            e.printStackTrace();
//            返回错误响应
            return new ChatResponse(false,"请求失败"+e.getMessage(), null);
        }
    }
/**
 * 获取用户聊天历史
 */
    @Override
    public String getChatHistory(String userId){
        try{
            List<ChatHistory> histories = chatHistoryRepository.findByUserIdOrderByCreateTimeDesc(userId);
            StringBuilder historyBuilder = new StringBuilder();
            for (ChatHistory history:histories){
                historyBuilder.append("用户：").append(history.getUserMessage()).append("\n");
                historyBuilder.append("AI：").append(history.getAiResponse()).append("\n\n");

            }
            return historyBuilder.toString();
        }catch (Exception e){
            e.printStackTrace();
            return "获取聊天历史失败：" + e.getMessage();
        }
    }
}
